#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
凯利公式计算器快速启动脚本
功能说明：一键启动Streamlit应用的简化脚本
作者：luohe
创建时间：2024-12-19
修改时间：2024-12-19
"""

import os
import sys
import subprocess
import webbrowser
import time
from pathlib import Path

def check_dependencies():
    """检查必要的依赖包"""
    required_packages = [
        'streamlit',
        'numpy',
        'pandas',
        'plotly',
        'matplotlib'
    ]
    
    missing_packages = []
    
    for package in required_packages:
        try:
            __import__(package)
            print(f"✓ {package} 已安装")
        except ImportError:
            missing_packages.append(package)
            print(f"❌ {package} 未安装")
    
    if missing_packages:
        print(f"\n缺少以下依赖包: {', '.join(missing_packages)}")
        print("正在自动安装...")
        
        try:
            subprocess.run([
                sys.executable, "-m", "pip", "install", "-r", "requirements.txt"
            ], check=True)
            print("✅ 依赖包安装完成")
            return True
        except subprocess.CalledProcessError:
            print("❌ 依赖包安装失败，请手动运行: pip install -r requirements.txt")
            return False
    
    return True

def start_streamlit_app():
    """启动Streamlit应用"""
    app_file = "streamlit_kelly_calculator.py"
    
    if not os.path.exists(app_file):
        print(f"❌ 找不到应用文件: {app_file}")
        return False
    
    print("🚀 正在启动凯利公式计算器...")
    
    try:
        # 启动Streamlit应用
        process = subprocess.Popen([
            sys.executable, "-m", "streamlit", "run", app_file,
            "--server.port=8501",
            "--server.address=localhost",
            "--browser.gatherUsageStats=false"
        ])
        
        # 等待服务器启动
        print("⏳ 等待服务器启动...")
        time.sleep(3)
        
        # 自动打开浏览器
        url = "http://localhost:8501"
        print(f"🌐 正在打开浏览器: {url}")
        webbrowser.open(url)
        
        print("\n" + "="*50)
        print("🎉 凯利公式计算器已成功启动！")
        print(f"📱 访问地址: {url}")
        print("⏹️  按 Ctrl+C 停止服务器")
        print("="*50 + "\n")
        
        # 等待用户中断
        try:
            process.wait()
        except KeyboardInterrupt:
            print("\n🛑 正在停止服务器...")
            process.terminate()
            process.wait()
            print("✅ 服务器已停止")
        
        return True
        
    except FileNotFoundError:
        print("❌ 找不到Streamlit命令，请确保已正确安装Streamlit")
        print("💡 尝试运行: pip install streamlit")
        return False
    except Exception as e:
        print(f"❌ 启动失败: {str(e)}")
        return False

def main():
    """主函数"""
    print("📊 凯利公式计算器 - 快速启动")
    print("="*40)
    
    # 检查当前目录
    current_dir = Path.cwd()
    print(f"📁 当前目录: {current_dir}")
    
    # 检查依赖
    print("\n🔍 检查依赖包...")
    if not check_dependencies():
        print("\n❌ 依赖检查失败，请手动安装依赖包后重试")
        input("按回车键退出...")
        return
    
    # 启动应用
    print("\n🚀 启动应用...")
    if start_streamlit_app():
        print("\n👋 感谢使用凯利公式计算器！")
    else:
        print("\n❌ 启动失败，请检查错误信息")
        input("按回车键退出...")

if __name__ == "__main__":
    try:
        main()
    except KeyboardInterrupt:
        print("\n\n👋 用户取消操作，程序退出")
    except Exception as e:
        print(f"\n❌ 程序异常: {str(e)}")
        input("按回车键退出...")